﻿using SigowayCommonLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;

using System.Windows.Forms;
using WarehouseManager.Common;

namespace WarehouseManager.View
{
    public partial class BillHistoryForm : Form
    {
        private BackgroundWorker m_BackgroundWorker;
        private BL.BillCreateBL blBillCreate;
        private DataTable datSource = new DataTable();
        public BillHistoryForm(string _operatorName)
        {
            InitializeComponent();
            Init(_operatorName);
        }

        private void Init(string _operatorName)
        {
            this.lblOperator.Text = _operatorName;
            this.lblOperatDate.Text = DateTimeUtil.GetCurrentDate();

            this.blBillCreate = new BL.BillCreateBL();
            this.dateFrom.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
            this.dateFrom.Focus();
            #region BackgroundWorker
            m_BackgroundWorker = new BackgroundWorker();
            m_BackgroundWorker.WorkerReportsProgress = true;
            m_BackgroundWorker.WorkerSupportsCancellation = true;
            m_BackgroundWorker.DoWork += new DoWorkEventHandler(DoWork);
            m_BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedWork);
            #endregion
        }
        void DoWork(object sender, DoWorkEventArgs e)
        {
            DataTable datPrint = CreateTable();
            DataRow darPrintRow = null;
            foreach (DataRow dar in datSource.Rows)
            {
                darPrintRow = datPrint.NewRow();
                darPrintRow["DrugName"] = dar["DrugName"];
                darPrintRow["DrugSpec"] = dar["DrugSpec"];
                darPrintRow["DrugCount"] = dar["DrugCount"];
                darPrintRow["unit"] = dar["unit"];
                darPrintRow["PatientName"] = dar["PatientName"];
                darPrintRow["MobileNo"] = dar["MobileNo"];
                darPrintRow["Addr"] = dar["Addr"];
                datPrint.Rows.Add(darPrintRow);
            }
            List<string> lstTemp = new List<string>();
            lstTemp.Add(this.lblOperator.Text);
            lstTemp.Add(dateFrom.Value.ToString("yyyy/MM/dd"));
            lstTemp.Add(dateTo.Value.ToString("yyyy/MM/dd"));            
            Print print = new Print();
                     
            print.BuShu = 1;
            print.DoPrintBillHistory(datPrint, lstTemp);
        }

        void CompletedWork(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBoxHelp.ShowMsgError("打印失败!");
                LogManager.WriteLine("打印失败!Exception={0}", e.Error);
            }
            else if (e.Cancelled)
            {
                MessageBoxHelp.ShowMsgWarning("打印取消");
            }
            else
            {
                MessageBoxHelp.ShowMsgInfor("打印完了");
            }
            this.Enabled = true;
            this.btnPrint.Enabled = true;
            this.btnPrint.Text = "打印";
        }
        private DataTable CreateTable()
        {
            DataTable datTemp = new DataTable();
            datTemp.Columns.Add("DrugName", typeof(string));
            datTemp.Columns.Add("DrugSpec", typeof(string));
            datTemp.Columns.Add("DrugCount", typeof(string));
            datTemp.Columns.Add("unit", typeof(string));
            datTemp.Columns.Add("PatientName", typeof(string));
            datTemp.Columns.Add("MobileNo", typeof(string));
            datTemp.Columns.Add("Addr", typeof(string));
            return datTemp;
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.dataGridList.Rows.Count > 0)
                {
                    this.dataGridList.Rows.Clear();
                }

                datSource = this.blBillCreate.getBillList(this.dateFrom.Value, this.dateTo.Value);
                if (datSource == null)
                {
                    this.btnSave.Enabled = false;
                    this.btnPrint.Enabled = false;
                    MessageBoxHelp.ShowMsgInfor("开票日期范围内没有记录！");
                    return;
                }
                foreach (DataRow datRow in datSource.Rows)
                {
                    this.dataGridList.Rows.Add(datRow[ConstInfo.COL_DRUGNAME],
                        datRow[ConstInfo.COL_DRUGSPEC],
                        datRow[ConstInfo.COL_DRUGCOUNT],
                        datRow[ConstInfo.COL_UNIT],
                        datRow[ConstInfo.COL_PATIENT_NAME],
                        datRow[ConstInfo.COL_MOBILENO],
                        datRow[ConstInfo.COL_ADDR]);
                }
                this.btnSave.Enabled = true;
                this.btnPrint.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBoxHelp.ShowMsgError("出票履历信息查询失败!");
                LogManager.WriteLine("出票履历信息查询失败!Exception={0}", ex);
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
           if (null == datSource || datSource.Rows.Count < 1)
            {
                MessageBoxHelp.ShowMsgWarning("没有可打印的信息");
                return;
            }
            this.Enabled = false;
            this.btnPrint.Enabled = false;
            this.btnPrint.Text = "打印中";
            m_BackgroundWorker.RunWorkerAsync();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog sfDialog = new SaveFileDialog();
                sfDialog.AddExtension = true;
                sfDialog.DefaultExt = ".csv";
                sfDialog.FileName = "出票履历_" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
                sfDialog.Title = "出票履历保存";
                sfDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                if (sfDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                using (StreamWriter sw = new StreamWriter(sfDialog.FileName, false, Encoding.UTF8))
                {
                    sw.AutoFlush = true;
                    string strTitle = string.Empty;

                    for (int colIndex = 0; colIndex < this.dataGridList.Columns.Count; colIndex++)
                    {
                        strTitle += this.dataGridList.Columns[colIndex].HeaderText + ",";
                    }
                    sw.WriteLine(strTitle.Remove(strTitle.Length - 1, 1));

                    foreach (DataGridViewRow item in this.dataGridList.Rows)
                    {
                        string strData = string.Format("{0},{1},{2},{3},{4},{5},{6}", item.Cells[ConstInfo.COL_DRUGNAME].Value,
                            item.Cells[ConstInfo.COL_DRUGSPEC].Value,
                            item.Cells[ConstInfo.COL_DRUGCOUNT].Value,
                            item.Cells[ConstInfo.COL_UNIT].Value,
                            item.Cells[ConstInfo.COL_PATIENT_NAME].Value,
                            item.Cells[ConstInfo.COL_MOBILENO].Value,
                            item.Cells[ConstInfo.COL_ADDR].Value);

                        sw.WriteLine(strData);
                    }
                    sw.Close();
                }

                MessageBoxHelp.ShowMsgInfor("出票履历信息保存成功！");
            }
            catch (Exception ex)
            {
                MessageBoxHelp.ShowMsgInfor("出票履历信息保存成功！");
                LogManager.WriteLine("出票履历信息保存成功!Exception={0}", ex);
            }
        }
    }
}